package com.tang.common.interceptor.frequency;

import com.tang.common.constant.ParamName;
import com.tang.common.exception.GeneralFilterHandlingException;
import com.tang.common.exception.GlobalException;
import com.tang.common.exception.NoRestrictionException;
import com.tang.common.interceptor.AbstractInterceptorHandler;
import com.tang.common.utils.CommonUtils;
import com.tang.common.utils.cache.ParamCache;
import javassist.ClassClassPath;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;
import org.springframework.core.io.Resource;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;

/**
 * 拦截器作用是验证指定ip的访问速率是否超时
 * @author tang
 * @date 2022/3/25 12:38
 */
@Order(1)
@Component
public class GlobalIpSpeedInterceptor extends AbstractInterceptorHandler {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public void doFilter(HttpServletRequest request, HttpServletResponse response) {
        //限制速率
        String enable = null;
        try {
            //获取速率
            enable = ParamCache.getValue(ParamName.GLOBAL_IP_SPEED);
        } catch (GlobalException e) {
            //如果没用获取到就不需要限制
            throw new NoRestrictionException("系统未开启ip访问速率限制");
        }
        //获得接口标记
        String sign = request.getMethod() + request.getRequestURI();
        //ip
        String ip = CommonUtils.getIpAddr(request);
        //设置lua脚本
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setResultType(Long.TYPE);
        redisScript.setLocation(new ClassPathResource("lua/globalIpSpeed.lua"));
        Long execute = stringRedisTemplate.execute(redisScript, Collections.singletonList(ip + sign), enable);
        //速率上限
        if (execute == 0){
            throw new GeneralFilterHandlingException("操作太快啦，喝口水再试试！！");
        }
    }
}
